import Database from '@tauri-apps/plugin-sql';
import {DownloadInfo} from "#/model.ts";
import {useDebounceFn} from "@vueuse/core";

class DbManager {
  db: Database | null = null;

  async init() {
    try {
      this.db = await Database.load('sqlite:download_manager.db');
    } catch (err) {
      console.error('🚀 ~ err:', err);
    }
  }

  async delDownloadInfo(id: string) {
    try {
      await this.db?.execute(`
          delete
          from download_table
          where id = $1
      `, [id])
    } catch (err) {
      console.error('🚀 ~ err:', err);
    }
  }

  setDownloadInfo = useDebounceFn(async (info: DownloadInfo) => {
    try {
      await this.db?.execute(
        `INSERT
        OR REPLACE into download_table 
           (id,url,name,size,downloaded_size,status,output,speed,progress,time) 
           VALUES (
        $1,
        $2,
        $3,
        $4,
        $5,
        $6,
        $7,
        $8,
        $9,
        $10
        )`,
        [info.id, info.url, info.name, info.size,
          info.downloaded_size, info.status, info.output,
          info.speed, info.progress, info.time],
      );
    } catch (err) {
      console.error('🚀 ~ err:', err);
    }
  }, 100)

  async getList() {
    let result: DownloadInfo[] = []
    try {
      result = await this.db?.select<DownloadInfo[]>(
        "SELECT * from download_table order by time desc"
      ) || []
    } catch (err) {
      console.error('🚀 ~ err:', err);
    }
    return result
  }
}

export default new DbManager()

